package backtracking;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class solveSudoku {
    List<LinkedList<Integer>> table = new ArrayList<>();
    public void solveSudoku(char[][] board) {
        for (int i = 0; i < 9; i++) {
            table.add(new LinkedList<>());
        }
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.'){
                    table.get((i/3)*3 + (j/3)).add(board[i][j] - '0');
                }
            }
        }
        backtracking(board);
    }
    public boolean backtracking(char[][] board){
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') continue;
                for (int k = 1; k <= 9; k++){
                    if (isValid(board, i, j, k)){
                        board[i][j] = (char) ('0' + k);
                        table.get((i / 3) * 3 + (j / 3)).add(k);
                        if (backtracking(board)){
                            return true;
                        }
                        board[i][j] = '.';
                        table.get((i / 3) * 3 + (j / 3)).removeLast();
                    }
                }
                return false;
            }
        }
        return true;
    }
    public boolean isValid(char[][] board, int row, int col, int content){
        for (int i = 0; i < 9; i++) {
            if (board[i][col] == (char) ('0' + content)){
                return false;
            }
        }
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == (char) ('0' + content)){
                return false;
            }
        }
        if (table.get((row / 3) * 3 + (col / 3)).contains(content)) return false;
        return true;
    }
}
